/*实现级联勾选开始*/
var nodeCheckedSilent = false;
function nodeChecked (event, node){
    if(nodeCheckedSilent){
        return;
    }
    nodeCheckedSilent = true;
    checkAllParent(node);
    checkAllSon(node);
    nodeCheckedSilent = false;
}

var nodeUncheckedSilent = false;
function nodeUnchecked  (event, node){
    if(nodeUncheckedSilent)
        return;
    nodeUncheckedSilent = true;
    uncheckAllParent(node);
    uncheckAllSon(node);
    nodeUncheckedSilent = false;
}

//选中全部父节点
function checkAllParent(node){
    $('#tree').treeview('checkNode',node.nodeId,{silent:true});
    var parentNode = $('#tree').treeview('getParent',node.nodeId);
    if(!("nodeId" in parentNode)){
        return;
    }else{
        checkAllParent(parentNode);
    }
}
//取消全部父节点
function uncheckAllParent(node){
    $('#tree').treeview('uncheckNode',node.nodeId,{silent:true});
    var siblings = $('#tree').treeview('getSiblings', node.nodeId);
    var parentNode = $('#tree').treeview('getParent',node.nodeId);
    if(!("nodeId" in parentNode)) {
        return;
    }
    var isAllUnchecked = true;  //是否全部没选中
    for(var i in siblings){
        if(siblings[i].state.checked){
            isAllUnchecked=false;
            break;
        }
    }
    if(isAllUnchecked){
        uncheckAllParent(parentNode);
    }

}

//级联选中所有子节点
function checkAllSon(node){
    $('#tree').treeview('checkNode',node.nodeId,{silent:true});
    if(node.nodes!=null&&node.nodes.length>0){
        for(var i in node.nodes){
            checkAllSon(node.nodes[i]);
        }
    }
}
//级联取消所有子节点
function uncheckAllSon(node){
    $('#tree').treeview('uncheckNode',node.nodeId,{silent:true});
    if(node.nodes!=null&&node.nodes.length>0){
        for(var i in node.nodes){
            uncheckAllSon(node.nodes[i]);
        }
    }
}
/*实现级联勾选结束*/




/*初始化添加角色方法 和 角色授权方法*/
$(function () {
    initAdd();
    initGrant();
    initUpdate();
});




/*格式化状态*/
function formatState(state) {
    return state==1?'启用':'禁用';
}

/*格式化操作*/
function formatOption() {
    var del = "<a href='javascript:void(0);' class='del'><i class='glyphicon glyphicon-trash'></i></a>";
    var edit = "<a href='javascript:void(0);' class='edit'><i class='glyphicon glyphicon-edit'></i></a>";
    return del+"&nbsp;&nbsp;&nbsp;&nbsp;"+edit;
}

window.optEvents={
    "click .del":function (e,value,row) {
        deleteRole(row.roleId,row.roleLabel);
    },"click .edit":function (e,value,row) {
        updateRole(row);
    }
}

/*修改角色信息*/
function updateRole(row){
    $("#update form #createTime").val(row.createTime);
    $("#update form").setForm(row);
    $("#update").dialog("open");
}

/*删除角色*/
function deleteRole(roleId,roleLabel) {

    swal({
        title:"信息提示！",
        text:"确定要删除"+roleLabel+"这个角色吗!",
        type:"warning",
        showCancelButton:true,
        confirmButtonText:"是的",
        confirmButtonColor:"green",
        cancelButtonText:"取消",
        cancelButtonColor:"#c00",
        allowOutsideClick:false
    }).then(function () {
        $.ajax({
            url:ctx+"/sys/role/getUserByRoleId",
            data:"roleId="+roleId,
            dataType:"json",
            async:false,
            success:function(arr){
                if(arr.length>0){
                    swal("信息提示！","这个角色有用户存在，不能删除!","warning");
                    return;
                }else{
                    $.ajax({
                        url:ctx+"/sys/role/deleteRole",
                        data:"roleId="+roleId,
                        dataType:"text",
                        async:false,
                        success:function(msg) {
                            var flag = "";
                            if(msg=="角色删除失败"){
                                flag = "info";
                            }else{
                                flag = "success";
                            }
                            swal("信息提示!",msg,flag);
                            $("#roleTable").bootstrapTable("refresh");
                        }
                    });
                }
            }
        });
    });

}

/*获取角色详情*/
function getDetail(index,row){
    var roleId = row.roleId;
    console.info(roleId);
    var html = "";
    $.ajax({
        url:ctx+"/sys/role/getUserByRoleId",
        data:"roleId="+roleId,
        dataType:"json",
        async:false,
        success:function(arr){
            if(arr.length>0){
                var strs = "";
                $(arr).each(function () {
                    var str = "<tr><td>"+this.userName+"</td>" +
                        "<td>"+this.loginName+"</td>" +
                        "<td>"+(this.gender==0?'女':'男')+"</td>" +
                        "<td>"+this.address+"</td></tr>";
                    strs+=str;
                });
                var $table = "<table  id='tempTable'><thead><tr>" +
                    "<th>用户姓名</th>" +
                    "<th>登录名</th>" +
                    "<th>性别</th>" +
                    "<th>地址</th>" +
                    "</tr></thead>" +
                    "<tbody>" +strs
                    "</tbody></table>";
                html+=$table;
            }else{
                html = '<span style="color:#CE5454;">此角色没有用户!</span>';
            }
        }
    });
    return html;
}
/*添加角色方法*/
function initAdd() {
    $("#add").dialog({
         title:'添加角色',
         btnValue:'添加',
        btnBind:function () {
            var param = $(".modal-body").find("#add_form").serialize();
            var roleName =  $(".modal-body #add_form").find("[name='roleName']").val();
            if(roleName==null || roleName==''){
                swal("角色姓名不能为空","","warning");
                return;
            }
            $.post(ctx+"/sys/role/add",param,function (msg) {
                toastr.success(msg);
                $("#roleTable").bootstrapTable("refresh");
                $("#add").dialog("close");
                $("#roleTable").bootstrapTable("uncheckAll");
            },'text');
        }
    });
}

/*初始化修改方法*/
function initUpdate() {
    $("#update").dialog({
        title:'修改角色',
        btnValue:'修改',
        btnBind:function () {
            var param = $(".modal-body").find("#update_form").serialize();
            console.info(param);
            var roleName =  $(".modal-body #update_form").find("[name='roleName']").val();
            if(roleName==null || roleName==''){
                swal("角色姓名不能为空","","warning");
                return;
            }
            $.post(ctx+"/sys/role/update",param,function (msg) {
                toastr.success(msg);
                $("#roleTable").bootstrapTable("refresh");
                $("#update").dialog("close");
                $("#roleTable").bootstrapTable("uncheckAll");
            },'text');
        }
    });
}



function prepareAdd() {
    $("#add").find("form")[0].reset();
    $("#add").dialog("open");
}

/*初始化授权方法*/
function initGrant() {
    $("#grant").dialog({
        title:"角色授权",
        btnValue:"授权",
        btnBind:function () {
            var rows = $("#roleTable").bootstrapTable("getSelections");
            var param = "roleId="+rows[0].roleId;
            var arr = $("#tree").treeview("getChecked");
            $(arr).each(function () {
                param = param+"&menuIds="+this.id;
            });
            $.post(ctx+"/sys/permission/grant",param,function (msg) {
                toastr.success(msg);
                $("#grant").dialog("close");
                $("#roleTable").bootstrapTable("uncheckAll");
            });
        }
    });
}

/*点击授权显示已授权信息*/
function grant() {
    var rows = $("#roleTable").bootstrapTable("getSelections");
    if(rows.length!=1){
        swal("请至少选中一条且只能是一条待授权");
        return;
    }

    var roleId = "roleId="+rows[0].roleId;
    $.getJSON(ctx+"/sys/permission/getTree?_="+new Date().getTime(),roleId,function (result) {
      $("#tree").treeview({
          data:result,
          showCheckbox:true,
          multiSelect:true,
          onNodeChecked:nodeChecked ,
          onNodeUnchecked:nodeUnchecked
      });
    });
    $("#grant").dialog("open");
}

